<?php

namespace App\Services\Product\UserService;

use App\Facades\UserManager;
use App\Facades\WeChatService as WeChat;
use Cache;
use Carbon\Carbon;
use DB;
use Sentinel;

class WxUserService
{

    /**
     * 创建或更新用户微信账号 openid 信息
     * @param  string  $code        授权 code
     */
    public function add($code)
    {

        $oAuthAccessToken = WeChat::oAuthAccessToken($code);

        if ($oAuthAccessToken)
        {
            $userInfo = WeChat::getUserInfo($oAuthAccessToken);
            
            session(['openId' => $userInfo['openid']]);
            
            $user = Sentinel::findByCredentials(['username' => $userInfo['openid']]);

            if (is_null($user))
            {
                $user = Sentinel::registerAndActivate([
                    'username' => $userInfo['openid'],
                    'password' => 'password',
                ]);

                $wxUser = UserManager::addWxUser([
                    'user_id' => $user->id,
                    'open_id' => $userInfo['openid'],
                    'nickname' => $userInfo['nickname'],
                    'head_img_url' => $userInfo['headimgurl'],
                    'sex' => $userInfo['sex'],
                    'city' => $userInfo['city'],
                    'province' => $userInfo['province'],
                    'country' => $userInfo['country'],
                    ]);
                Cache::put($userInfo['openid'], $wxUser, Carbon::now()->addMinutes(env('CACHE_USER_TIME', 1)));
            }else{
                try{
                    $user->wxUser()->update([
                        'nickname' => $userInfo['nickname'],
                        'head_img_url' => $userInfo['headimgurl'],
                        'sex' => $userInfo['sex'],
                        'city' => $userInfo['city'],
                        'province' => $userInfo['province'],
                        'country' => $userInfo['country'],
                        ]);
                }catch(Excetion $e){
                    throw new UserException('add');
                }
            }
            Sentinel::login($user);
        }

    }

    /**
     * 获取用户信息
     * @return [type] 
     */
    public function getUserInfo()
    {
        $wxUser = UserManager::getWxUser();
        $wxUser->load(['userInfo' => function($query){
            $query->select([
                'user_id',
                'name',
                'head_img',
                'birthday',
                'nickname',
                'address',
                'phone',
                'email',
                'sex',
                ]);
        }]);
        return $wxUser->userInfo;
    }

    /**
     * 添加用户信息
     * @param [type] $data 
     */
    public function addUserInfo($data)
    {
        $wxUser = UserManager::getWxUser();
        if($data['sex'] == '男'){
            $data['sex'] = 1;
        }
        else if($data['sex'] == '女'){
            $data['sex'] = 2;
        }else{
            $data['sex'] = 0;
        }
        $data = array_merge($data, ['user_id' => $wxUser->user_id]);
        UserManager::addUserInfo($data);
    }

    public function addDefaultUserinfo()
    {
        $wxUser = UserManager::getWxUser();

        $data = [
            'user_id' => $wxUser->user_id,
            'sex' => 0
            ];
        UserManager::addUserInfo($data);
    }

    /**
     * 获取微信用户列表包含用户信息
     * @param  [type] $openId 
     * @param  [type] $phone    
     * @return [type]           
     */
    public function getWxUserListWithUserInfo($openId, $phone)
    {
        $query = UserManager::getAllUserInfo();
        $query = $query->with(['wxUser' => function($query){
                        $query->with(['devices'])->select(['user_id', 'open_id', 'current_device_code']);
                    }]);

        if(!empty($openId))
        {
            $userIds = UserManager::findWxUserByOpenId($openId)->select('user_id')->get();
            $query = $query->whereIn('user_id', $userIds);
        }

        if(!empty($phone))
        {
            $query = $query->where('phone', 'like', '%'.$phone.'%');
        }

        if(empty($openId) && empty($phone)){
            $query->orWhereExists(function($query){
                    $query->select(DB::raw(1))
                        ->from('wx_user_devices')
                        ->whereRaw('wx_user_devices.user_id = user_infos.user_id');
                })
                ->orWhereNotNull('name')
                ->orWhereNotNull('address')
                ->orWhereNotNull('phone')
                ->orWhereNotNull('email');
        }

        return $query->select(['user_id', 'name', 'address', 'phone', 'email', 'sex'])
            ->orderBy('user_id', 'desc')->paginate(8);
    }


}
